;; Test for set! special form

;; 测试1: 基本的set!用法
(define x 10)
(display "x before set!: ")
(display x)
(display "\n")

(set! x 20)
(display "x after set!: ")
(display x)
(display "\n")

;; 测试2: 在函数内部使用set!修改全局变量
(define counter 0)

(define (increment)
  (set! counter (+ counter 1))
  counter)

(display "counter before increment: ")
(display counter)
(display "\n")

(increment)
(display "counter after first increment: ")
(display counter)
(display "\n")

(increment)
(display "counter after second increment: ")
(display counter)
(display "\n")

;; 测试3: 使用set!修改函数
(define (square x) (* x x))
(display "square of 5: ")
(display (square 5))
(display "\n")

(set! square (lambda (x) (* x x x)))
(display "new square (now cube) of 5: ")
(display (square 5))
(display "\n")

;; 测试4: 尝试设置未定义的变量（应该会报错）
;; (set! undefined-variable 42)
;; (display undefined-variable)
;; (display "\n")

;; 测试5: 嵌套作用域中的set!
(define outer 100)
(define (outer-func)
  (define inner 200)
  (display "outer in outer-func: ")
  (display outer)
  (display "\n")
  (display "inner in outer-func: ")
  (display inner)
  (display "\n")
  (set! outer (+ outer 10))
  (set! inner (+ inner 20))
  (display "outer after set! in outer-func: ")
  (display outer)
  (display "\n")
  (display "inner after set! in outer-func: ")
  (display inner)
  (display "\n")
  (define (inner-func)
    (display "outer in inner-func: ")
    (display outer)
    (display "\n")
    (display "inner in inner-func: ")
    (display inner)
    (display "\n")
    (set! outer (+ outer 5))
    (set! inner (+ inner 10))
    (display "outer after set! in inner-func: ")
    (display outer)
    (display "\n")
    (display "inner after set! in inner-func: ")
    (display inner)
    (display "\n"))
  (inner-func))

(outer-func)
(display "outer after outer-func: ")
(display outer)
(display "\n")
;; inner在outer-func外部不可见
;; (display "inner after outer-func: ")
;; (display inner)
;; (newline)

(exit)